/*
 ***************************************************************************************
 *  Copyright (C) 2006 EsperTech, Inc. All rights reserved.                            *
 *  http://www.espertech.com/esper                                                     *
 *  http://www.espertech.com                                                           *
 *  ---------------------------------------------------------------------------------- *
 *  The software in this package is published under the terms of the GPL license       *
 *  a copy of which has been included with this distribution in the license.txt file.  *
 ***************************************************************************************
 */
package com.espertech.esper.common.internal.epl.script.jsr223;

import com.espertech.esper.common.internal.epl.expression.core.ExprValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.*;

public class JSR223Helper {

    private static final Logger log = LoggerFactory.getLogger(JSR223Helper.class);

    public static ExpressionScriptCompiledJSR223 verifyCompileScript(String scriptName, String expression, String dialect) throws ExprValidationException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scripting = manager.getEngineByName(dialect);
        if (scripting == null) {
            throw new ExprValidationException("Failed to obtain script runtime for dialect '" + dialect + "' for script '" + scriptName + "'");
        }
        scripting.put(ScriptEngine.FILENAME, scriptName);

        Compilable compilingEngine = (Compilable) scripting;
        CompiledScript compiledScript;
        try {
            compiledScript = compilingEngine.compile(expression);
        } catch (ScriptException ex) {
            String message = "Exception compiling script '" + scriptName + "' of dialect '" + dialect + "': " + getScriptCompileMsg(ex);
            log.info(message, ex);
            throw new ExprValidationException(message, ex);
        }
        return new ExpressionScriptCompiledJSR223(compiledScript);
    }

    public static String getScriptCompileMsg(ScriptException ex) {
        if (ex.getLineNumber() != 1 && ex.getColumnNumber() != -1) {
            return "At line " + ex.getLineNumber() + " column " + ex.getColumnNumber() + ": " + ex.getMessage();
        } else {
            return ex.getMessage();
        }
    }
}
